package cn.czh0123.interceptor;

import cn.czh0123.config.MinioPropertiesConfig;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Component
public class MinioImageInterceptor implements HandlerInterceptor {

    @Resource
    private MinioPropertiesConfig minioPropertiesConfig;

    public static final String PREVIEW_PATH_PREFIX = "/preview";
    private static final String GET_METHOD = "GET";
    private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";  // 默认类型

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler)
            throws IOException {
        String requestUri = request.getRequestURI();
        String imagePath = requestUri.substring(PREVIEW_PATH_PREFIX.length());

        String minioUrl = minioPropertiesConfig.getEndpoint() + imagePath;

        // 发送请求到 MinIO 获取图片
        HttpURLConnection connection = (HttpURLConnection) new URL(minioUrl).openConnection();
        connection.setRequestMethod(GET_METHOD);
        connection.setDoInput(true);

        try (InputStream inputStream = connection.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {

            // 设置响应头
            // 获取响应头中的 Content-Type 动态设置响应头
            String contentType = connection.getHeaderField("Content-Type");
            if (contentType != null) {
                response.setContentType(contentType);
            } else {
                response.setContentType(DEFAULT_CONTENT_TYPE);  // 默认类型
            }
            response.setHeader("Content-Disposition", "inline; filename=" + imagePath);

            // 将 MinIO 返回的文件流写入响应流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            response.flushBuffer();
            return false;  // 返回 false 表示拦截器已处理请求，后续的 Controller 方法不会被执行
        } catch (IOException e) {
            log.error("Error retrieving image: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error retrieving image.");
            return false;
        }
    }
}
